//
//  SearchViewController.m
//  XDCommonApp
//
//  Created by XD-XY on 3/15/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "SearchViewController.h"
#import "searchResultCell.h"
#import "XDHeader.h"
#import "XDTools.h"
#import "MostDetailViewController.h"
@interface SearchViewController ()
{
    int page;
    BOOL isHeaderRefresh;
    BOOL isHaveMoreData;
}
@end

@implementation SearchViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _dataArray = [NSMutableArray arrayWithCapacity:4];
    page = 0;
    isHeaderRefresh = YES;
    isHaveMoreData = YES;
	// Do any additional setup after loading the view.
    self.titleLabel.text = [NSString stringWithFormat:@"\"%@\"的搜索结果",self.titleStr];
    self.titleLabel.textColor = TEXTBLACKCOLORE;
    
    self.tableView = [[UITableView alloc] initWithFrame:self.contentView.bounds style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:_tableView];
    [self getSearchDatas];
    
//    cheader = [[MJRefreshHeaderView  alloc] init];
//    cheader.delegate = self;
//    cheader.scrollView= _tableView;
//    
//    cfooter = [[MJRefreshFooterView alloc] init];
//    cfooter.delegate = self;
//    cfooter.scrollView = _tableView;
}
//进入刷新就会调用
-(void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    
    if (refreshView == cheader){
        isHeaderRefresh = YES;
    }else{
        isHeaderRefresh =NO;
    }
    

    [self getSearchDatas];
    
    //    [dict setObject:@"一页面" forKey:@"页面"];
    //    [NSTimer scheduledTimerWithTimeInterval:0.4 target:self selector:@selector(getNewData:) userInfo:dict repeats:NO];
}

//-(void)getNewData:(NSTimer *)timer
//{
//    NSString * str = [[timer userInfo] objectForKey:@"页面"];
//
//    [self getDatas];
//}

-(void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{
    if (refreshView == cfooter){
        
        //这里还要判断一下是不是加载没数据，如果没有数据，就执行下面两行，这样就能解决上拉箭头不下了的bug
        if (!isHaveMoreData){

//            DDLOG(@"point = %f,point = %f",point.x,point.y);
        }
    }else{
        
    }
}
#pragma mark ======================uitableview delegate=========================
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 170/2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellName = @"cell";
    searchResultCell * cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if (cell == nil){
        cell = [[searchResultCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
        cell.backgroundColor = [UIColor clearColor];
    }
    NSDictionary *dic = [_dataArray objectAtIndex:indexPath.row];
    cell.heardImageView.backgroundColor = [UIColor blackColor];
    cell.titleLabel.text = [dic objectForKey:@"workTitle"];
    cell.authorLabel.text = [dic objectForKey:@"author"];
    cell.boothLabel.text = @"A17展区,";
    cell.galleryLabel.text = [dic objectForKey:@"workBelongGallery"];
    cell.browseLabel.text = [NSString stringWithFormat:@"%@",[dic objectForKey:@"beScanTime"]];
    if (indexPath.row == 1){
//        cell.boothLabel.text = @"A17展区7展区,";
//        cell.galleryLabel.text = @"张三画廊";
//        cell.browseLabel.text = @"1527展区";
    }
    
    CGRect rect = [XDTools xyAutoSizeOfWidget:cell.boothLabel andSize:CGSizeMake(110, 12.5) andtextFont:12.5];
    cell.boothLabel.frame =rect;
    cell.galleryLabel.frame = CGRectMake(width_x(cell.boothLabel),rect.origin.y+1, 100, 12.5);
    
    CGRect rect2 = [XDTools xyAutoSizeOfWidget:cell.browseLabel andSize:CGSizeMake(100, 11) andtextFont:11];
    cell.browseLabel.frame = CGRectMake(UI_SCREEN_WIDTH-rect2.size.width-15, rect2.origin.y-2, rect2.size.width,170/2.0f);
    cell.rightImageView.frame = CGRectMake(cell.browseLabel.frame.origin.x-6-12,73/2.0f, 24/2, 16/2);
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dic = [_dataArray objectAtIndex:indexPath.row];
    MostDetailViewController *mostVC = [[MostDetailViewController alloc] init];
    mostVC.idStr = [dic objectForKey:@"id"];
    [self.navigationController pushViewController:mostVC animated:YES];
    
}

-(void)getSearchDatas{
    if ([XDTools NetworkReachable]){
        isHaveMoreData = YES;
        int oldPage = page;
        if (isHeaderRefresh){
            page = 0;
        }else{
            page++;
        }
        DDLOG(@"************************page = %d",page);
//        NSString * pageStr = [NSString stringWithFormat:@"%d",page];
        
        NSString *body = [NSString stringWithFormat:@" <ActivityDetailSearchByKey xmlns=\"http://tempuri.org/\">"
                          "<key>%@</key>"
                          "<activityId>%@</activityId>"
                          "</ActivityDetailSearchByKey>",self.titleStr,_activityId];
        
        __weak ASIFormDataRequest *request = [XDTools postRequestWithDict:body API:ORGNIZATIONLISTBYKEY];
        [request setCompletionBlock:^{
            [XDTools hideProgress:self.contentView];
            //[XDTools hideProgress:self.contentView];
            NSString *responseString = [request responseString];
            // NSDictionary *tempDic = [XDTools  JSonFromString:responseString];
            //DDLOG(@"responseString:%@", responseString);
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            int statusCode = [request responseStatusCode];
            NSString *soapAction = [[request requestHeaders] objectForKey:@"SOAPAction"];
            
            NSArray *arraySOAP =[soapAction componentsSeparatedByString:@"/"];
            int count = [arraySOAP count] - 1;
            NSString *methodName = [arraySOAP objectAtIndex:count];
            
            // Use when fetching text data
            NSString *result = nil;
            if (statusCode == 200) {
                //表示正常请求
//                if(page == 0){
//                    [_dataArray removeAllObjects];
//                }
                result = [SoapXmlParseHelper SoapMessageResultXml:responseString ServiceMethodName:methodName];
                NSDictionary  *responseDict = [XDTools JSonFromString:result];
                DDLOG(@"respodic = %@",responseDict);
                if ([[responseDict objectForKey:@"code"] intValue]==0){

                    NSArray *arr = [responseDict objectForKey:@"activityDetailSearchList"];
                    [_dataArray addObjectsFromArray:arr];
                    [_tableView reloadData];
                    
                    [cfooter endRefreshing];
                    [cheader endRefreshing];
                    
                    
                }else{
                    [XDTools showTips:@"数据获取失败" toView:self.contentView];
                }
            }
        }];
        
        [request setFailedBlock:^{
            page = oldPage;
            [XDTools hideProgress:self.contentView];
        }];
        
        [request startAsynchronous];
        [XDTools showProgress:self.contentView];
    }else{
        [XDTools showTips:brokenNetwork toView:self.contentView];
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
